﻿/**
 * \brief 验证线程定义
 * \file CVerifyThread.cc
 */

#include "CTcpTask.h"
#include "CTcpTaskPool.h"
#include "CVerifyThread.h"
#include "Log.h"

/// 构造函数
CVerifyThread::CVerifyThread(CTcpTaskPool* _pool, int _eventSize, std::string _threadName)
	:CTcpThread(_pool, _eventSize), CThread(_threadName)
{}

/// 析构函数
CVerifyThread::~CVerifyThread()
{}

/**
 * \brief 线程主回调函数
 */
void CVerifyThread::run()
{
	_task_list_iter iter, next;

	while(this->isEnd())
	{
		/// 等待队列进入任务列表
		this->shift();

		if(!_M_list.empty())
		{
			for(iter = this->_M_list.begin(), next = iter; iter != this->_M_list.end();)
			{
				++next;

				CTcpTask* pTask = *iter;
				/// 如果连接超时，删除这个任务
				if(pTask->checkVerifyTimeOut())
				{
					this->remove(iter);
					pTask->setRecycle();
					this->_M_pool->addRecycle(pTask);
				}

				/// 迭代器后移
				if(next != this->_M_list.end())
				{
					iter = next++;
				}
				else
				{
					/// 循环结束
					break;
				}
			}
		}

		int retcode = ::epoll_wait(this->_M_epfd, &this->_M_events, this->_M_eventSize, 0);

		/// 循环处理epoll事件
		if(retcode > 0)
		{
			int pos = 0;
			for(; pos < retcode; ++pos)
			{
				CTcpTask* pTask = (CTcpTask*)this->_M_events[pos].data.ptr;
				if(this->_M_events[pos].events & (EPOLLERR | EPOLLPRI))
				{
					this->remove(pTask);
					pTask->setRecycle();
					this->_M_pool->addRecycle(pTask);
				}
				else if(this->_M_events[pos].events & EPOLLIN)
				{
					switch(pTask->vCheckVerify())
					{
						/// 验证成功
						case 1:
							{
								this->remove(pTask);
								if(pTask->vCheckUnique())
								{
									pTask->vSetUnique();
									pTask->gotoNextState();
									this->_M_pool->addSync(pTask);
								}
								else
								{
									pTask->setRecycle();
									this->_M_pool->addRecycle(pTask);
								}
							}
							break;
						/// 验证超时
						case 0:
							{
								break;
							}
							break;
						/// 验证失败
						case -1:
							{
								this->remove(pTask);
								pTask->setRecycle();
								this->_M_pool->addRecycle(pTask);
							}
							break;
						default:
							{
							}
							break;
					}
				}
			}
		}

		/// sleep 50 毫秒，让其它线程获得CPU
		this->msleep(50);
	}

	/// 线程结束，所有任务进入回收线程
	for(iter = this->_M_list.begin(), next = iter; iter != this->_M_list.end();)
	{
		++next;
		CTcpTask* pTask = *iter;

		/// 删除这个任务
		this->remove(iter);
		pTask->setRecycle();
		this->_M_pool->addRecycle(pTask);

		/// 迭代器后移
		if(next != this->_M_list.end())
		{
			iter = next++;
		}
		else
		{
			/// 循环结束
			break;
		}
	}
}

/// 加入任务列表
void CVerifyThread::add(CTcpTask* _pTask)
{
	this->_M_list.push_back(_pTask);
	_pTask->addEpoll(this->_M_epfd, EPOLLIN | EPOLLERR | EPOLLPRI, (void*)(*iter));
	this->_M_eventSize = this->_M_list.size();
}

/// 从任务列表删除
void CVerifyThread::remove(_task_list_iter& _iter)
{
	if(_iter != this->_M_list.end())
	{
		(*_iter)->delEpoll(this->_M_epfd, EPOLLIN | EPOLLERR | EPOLLPRI);
		this->_M_list.erase(iter);
		this->_M_eventSize = this->_M_list.size();
	}
}

